<template>
	<coreshop-page title="申请售后" mode="left">
		<view class="layout-after-sales">
			<uv-alert type="warning" description="如果订单未发货，只需要勾选需要退款的产品即可，如果已经发货，可以设置需要退货的产品数量。"></uv-alert>

			<!-- 售后模式 -->
			<view class="after-sales-type">
				<view class="title">售后模式</view>
				<view class="radio-box">
					<uv-radio-group v-model="state.radioValue" activeColor="#D33123" @change="handleChangeRadio">
						<uv-radio :customStyle="{'margin-left': '30rpx'}" v-for="(item, index) in state.radiolist"
							:key="index" :label="item.name" :name="item.value" :disabled="item.disabled">
						</uv-radio>
					</uv-radio-group>
				</view>
			</view>

			<!-- 退货的商品 -->
			<view class="goods-list">
				<view class="goods-item" v-for="item,index in state.goodsList" :key="item.id">
					<view class="checkbox">
						<checkbox-group style="margin: auto" @change="handleToggleCheckbox($event,index)">
							<checkbox style="transform:scale(0.9)" color="#D33123" :value="item.id"
								:checked="item.checked" :disabled="item.disabled" />
						</checkbox-group>
					</view>
					<view class="goods-box">
						<view @click="handleChangeCheckbox(index)">
							<coreshop-goods-card type="horizontal" imgHeight="140rpx" imgWidth="140rpx"
								:goodsData="hanldeCombinationGoodsData(item)">
								<template #goodPrice>
									<view class="num-box">
										<view class="num">
											<text class="tit">购买数：{{ item.nums }}</text>
											<text class="tit">发货数量：{{ item.sendNums }}</text>
											<text class="tit">已退数量：{{ item.reshipNums }}</text>
										</view>
									</view>
								</template>
							</coreshop-goods-card>
						</view>
						<view class="returned-purchase"
							v-if="state.radioValue == RefundType.returnRefund &&  item.sendNums > 0">
							<text class="tit">您要退货的数量：</text>
							<uv-number-box v-model="item.returnNums" inputWidth="27" button-size="27"
								:disabledInput="true" :min="item.min" :max="item.max"
								@change="handleChangeGoodsNum($event,index)">
							</uv-number-box>
						</view>
					</view>
				</view>
			</view>

			<!-- 退款金额 -->
			<view class="returned-price">
				<view class="title">
					<view class="tit">退款金额</view>
					<view class="desc">
						<uv-input type="number" v-model="state.refundPrice" placeholder="请输入退款金额" border="surround"
							@blur="handleInputBlur">
							<template v-slot:prefix>
								<uv-text text="￥" type="tips"></uv-text>
							</template>
						</uv-input>
					</view>
				</view>
				<view class="brief">可修改，最多￥{{ state.maxRefund }}，含发货邮费￥{{ state.costFreight }}</view>
			</view>

			<!-- 上传凭证 -->
			<view class="upload-box">
				<view class="title">
					<view class="tit">上传凭证</view>
					<view class="desc">{{state.images.length}}/5</view>
				</view>
				<view class="m-t-20">
					<uv-upload :fileList="state.images" multiple :maxCount="5"
						@afterRead="(files: any) => handleUploadVoucher(files)"
						@delete="(files: any) => onDeleteImage(files)"></uv-upload>
				</view>
			</view>

			<!-- 问题描述 -->
			<view class="describe-box">
				<view class="title">
					问题描述
				</view>
				<view class="m-t-20">
					<uv-textarea v-model="state.reason" placeholder="请您在此描述问题"></uv-textarea>
				</view>
			</view>

			<!-- 按钮 -->
			<coreshop-fixed-bottom-button :loading="loading" title="提交"
				@onClick="handlesubmit()"></coreshop-fixed-bottom-button>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { handleShowToast, handleRouteNavigateTo } from '@/core/utils';
	import { queryOrderDetails, queryUploadImages, queryAddAftersales } from '@/core/api';
	import type { Response } from '@/core/models';
	import { OrderAllStatusTypeEnum, OrderShipStatusEnum } from '@/core/enum';
	import { amount } from '@/uni_modules/uv-ui-tools/libs/function/test.js';
	import { useLoadingFn } from '@/core/hooks';

	enum RefundType {
		/** 仅退款 */
		onlyRefund = '1',
		/** 退货退款 */
		returnRefund = '2'
	}

	interface QueryParams {
		orderId ?: string;
	}

	const state = reactive<{
		orderId : string;
		goodsList : Array<any>;
		radiolist : Array<{ name ?: string, disabled ?: boolean, value ?: RefundType }>;
		radioValue : string;
		maxRefund : number;   /** 最大可退金额 */
		costFreight : number; /** 运费 */
		refundShow : number;
		images : Array<any>;
		reason : string;
		refundPrice : number;  /** 退款金额 */
		payedAmount : number;   /** 订单金额 */
	}>({
		orderId: "",
		goodsList: [],
		radiolist: [{ value: RefundType.onlyRefund, name: '仅退款', disabled: false }, { value: RefundType.returnRefund, name: '退货退款', disabled: false }],
		radioValue: '1',
		maxRefund: 0,
		costFreight: 0,
		refundShow: 0,
		images: [],
		reason: "",
		refundPrice: 0,
		payedAmount: 0,
	});

	const loading = ref(false);
	const handlesubmit = useLoadingFn(onSubmit, loading)

	onLoad((query : QueryParams) => {
		if (query?.orderId) {
			state.orderId = query?.orderId;
			getOrderDetail();
		} else {
			handleShowToast('获取失败', 'error', () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500)
			})
		}
	});

	/** 获取订单详情 */
	const getOrderDetail = async () => {
		const orderDetail : Response<any> = await queryOrderDetails({ id: state.orderId });
		if (orderDetail.status) {
			/** 不是未支付的，已取消的，已完成的状态，才可以售后 */
			if (orderDetail.data.globalStatus != OrderAllStatusTypeEnum.aLL_PENDING_PAYMENT &&
				orderDetail.data.globalStatus != OrderAllStatusTypeEnum.aLL_COMPLETED &&
				orderDetail.data.globalStatus != OrderAllStatusTypeEnum.aLL_CANCEL) {

				/** 判断是已付款未发货，如果是，就禁用退货退款 */
				if (orderDetail.data.shipStatus != OrderShipStatusEnum.partialYes && orderDetail.data.shipStatus != OrderShipStatusEnum.yes) {
					state.radiolist[1].disabled = true;
				}

				/** 设置选中的商品 */
				state.goodsList = orderDetail.data.items.map((item : any) => {
					item['returnNums'] = 0;
					item['checked'] = false;
					item['disabled'] = (item.nums - item.reshipNums) <= 0;
					item['min'] = 0;

					if (orderDetail.data.shipStatus == OrderShipStatusEnum.no) {  // 未发货 
						item['max'] = item.nums;
					} else {
						item['max'] = item.sendNums - item.reshipNums;
					}
					return item;
				})
				state.payedAmount = orderDetail.data.payedAmount;
				state.maxRefund = (orderDetail.data.orderAmount * 10000 - orderDetail.data.refunded * 10000) / 10000;
				state.costFreight = orderDetail.data.costFreight;
				state.refundShow = (orderDetail.data.payedAmount * 10000 - orderDetail.data.refunded * 10000) / 10000;
			} else {
				uni.showModal({
					title: '提示',
					content: '订单不可以进行售后',
					showCancel: true,
					success: function (res) {
						if (res.confirm) {
							uni.navigateBack();
						}
					}
				});
			}
		} else {
			handleShowToast(orderDetail.msg)
		}
	}

	/** 售后模式选择 */
	const handleChangeRadio = () => {
		handleCalculatePrice();
	}

	/** 多选框选择 */
	const handleToggleCheckbox = (e : any, index : number) => {
		handleChangeCheckbox(index);
	}

	/** 商品选择点击 */
	const handleChangeCheckbox = (index : number) => {
		state.goodsList[index].checked = !state.goodsList[index].checked;
		handleCalculatePrice();
	}

	/** 退货数量步进器 */
	const handleChangeGoodsNum = (e : any, index : number) => {
		state.goodsList[index].returnNums = e.value;
		handleCalculatePrice();
	}

	/** 计算价格 */
	const handleCalculatePrice = () => {
		let total : number = 0;
		state.goodsList.forEach((item : any) => {
			if (item.checked) {
				/** 如果是仅退款，那么退货数量就是购买的数量 */
				if (state.radioValue == RefundType.onlyRefund) {
					total = (total * 100000 + item.price * 100000 * item.nums) / 100000;
				} else {
					total = (total * 100000 + item.price * 100000 * item.returnNums) / 100000;
				}
			}
		})
		state.refundPrice = total;
	}

	/** 退款金额失去焦点 */
	const handleInputBlur = () => {
		if (state.refundPrice > state.refundShow) {
			handleShowToast('退款金额过大');
		}
	}

	/** 上传图片 */
	const handleUploadVoucher = async (files : any,) => {
		if (!files?.file) {
			return;
		}
		let imgArr = [];
		const imgPromises = files.file.map(async (item : any) => {
			return new Promise(async (resolve) => {
				const img : Response<any> = await queryUploadImages(item.url);
				if (img.status) {
					imgArr.push(img?.data?.src)
					resolve(img?.data?.src);
				} else {
					handleShowToast('上传失败');
				}
			})
		});
		await Promise.all(imgPromises);
		state.images.push(...imgArr.map((url : string) => {
			return {
				url,
			}
		}));
	}

	/** 图片删除 */
	const onDeleteImage = (event : any) => {
		state.images.splice(event.index, 1);
	}

	/** 组合商品数据传入组件 */
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			id: item.id,
			image: item.imageUrl,
			name: item.name,
			brief: item.addon,
		}
	}

	/** 提交 */
	async function onSubmit() {
		if (state.payedAmount != 0 && !amount(state.refundPrice)) {
			handleShowToast('请输入正确金额'); return;
		}
		if (state.refundPrice > state.refundShow) {
			handleShowToast('退款金额过大'); return;
		}
		let itemIds : any = [];
		state.goodsList.forEach((item : any) => {
			if (item.checked) {
				itemIds.push({
					id: item.id,
					nums: item.sendNums > 0 ? item.returnNums : 0,
					sendNums: item.sendNums,
				})
			}
		})
		if (itemIds.length == 0) {
			handleShowToast('请选择要售后的商品'); return;
		}
		const aftersales : Response<any> = await queryAddAftersales({
			orderId: state.orderId,
			type: state.radioValue,
			items: itemIds,
			images: state.images?.map((item : any) => item.url),
			refund: state.refundPrice,
			reason: state.reason
		});
		if (aftersales.status) {
			handleShowToast('提交成功', 'success', () => {
				setTimeout(() => {
					handleRouteNavigateTo(`/pages/subpackage/member/order/detail/detail?orderId=${state.orderId}`);
				}, 1500);
			})
		} else {
			handleShowToast(aftersales.msg);
		}
	}
</script>
<style lang="scss" scoped>
	@import './apply.scss';
</style>